package pers.li.service;

import pers.li.dao.CategoryDao;
import pers.li.dao.GoodsDao;
import pers.li.model.Category;
import pers.li.model.Goods;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CategoryService {
    private final CategoryDao categoryDao = new CategoryDao();
    private final GoodsDao goodsDao = new GoodsDao();

    /**
     * 根据大类获取分类和商品
     * @return 商品和分类的封装map
     */
    public List<Map<String, Object>> getCategoryAndGoods() {
        List<Map<String, Object>> res = new ArrayList<>();
        //获取一级菜单
        List<Category> parents = categoryDao.getCategory().stream()
                .filter(category -> category.getParentid() == null)
                .collect(Collectors.toList());
        //获取二级菜单
        for (Category parent : parents) {
            Map<String, Object> vo = new HashMap<>();
            vo.put("parents", parent);
            List<Category> child = categoryDao.getCategoryByParentId(parent.getCateId()).stream()
                    .limit(3).collect(Collectors.toList());
            vo.put("child", child);
            //获取相应的商品
            List<Goods> collect = goodsDao.getGoodsByCateId(child.get(0).getCateId()).
                    stream().limit(6).collect(Collectors.toList());
            vo.put("goods", collect);
            res.add(vo);
        }
        return res;
    }

    public List<List<Category>> getCategory(){
        List<List<Category>> list = new ArrayList<>();
        List<Category> parents = categoryDao.getCategory().stream()
                .filter(category -> category.getParentid() == null)
                .collect(Collectors.toList());
        for (Category parent : parents) {
            List<Category> child = categoryDao.getCategoryByParentId(parent.getCateId());
            list.add(child);
        }
        return list;
    }

    public static void main(String[] args) {
        System.out.println(new CategoryService().getCategoryAndGoods());
    }
}
